package com.customer.ostrich.config;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author HuTongFu
 * @description: nacos config
 * @since 2019/6/20 16:51
 */
@Slf4j
@Configuration
public class NacosConfig {

    @Resource
    private SysCommonConfig sysCommonConfig;

    // 注入 Nacos 的 NamingService 实例
    @NacosInjected
    private NamingService namingService;

    @Value("${server.port}")
    private int serverPort;

    @Value("${spring.application.name}")
    private String applicationName;

    @PostConstruct
    public void registerInstance() throws NacosException {
        namingService.registerInstance(applicationName, sysCommonConfig.getNacosServerAddr(), serverPort);
        namingService.subscribe("nacos-customer", new EventListener() {
            @Override
            public void onEvent(Event event) {
                log.debug("获取注册的服务名=>{}", ((NamingEvent) event).getServiceName());
                log.debug("获取注册的服务实例=>{}", ((NamingEvent) event).getInstances());
            }
        });
    }


}
